﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Routing;
using Vit.Web.Providers;
using Vit.Common;
using Vit.Common.Models;
using Vit.Common.Providers;
using Vit.Mvc.Results;

namespace Vit.Mvc.Filters
{
    public class AuthorizationFilter : IAuthorizationFilter
    {
        private RouteCollection routes;
        private UnityService<IMembershipProvider> membership;

        public AuthorizationFilter(RouteCollection routes, UnityService<IMembershipProvider> membership)
        {
            this.routes = routes;
            this.membership = membership;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                string url = string.Format("{0}?return={1}", FormsAuthentication.LoginUrl, filterContext.HttpContext.Request.Url.AbsolutePath);
                filterContext.Result = new RedirectResult(url);
            }
            else
            {
                string area = filterContext.RouteData.DataTokens["area"] as string ?? "";
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                string uri = string.Format("{0}/{1}/{2}", area, controller, action).Replace("//", "/");
                IUser user = membership.Run<IUser>(p => p.GetCurrentUser(), o => o != null);
                if (!membership.Run<bool>(p => p.CheckOperationPermission(user, uri), o => o == true))
                {
                    filterContext.Result = new PartialUnauthorizedResult();
                }
            }
        }
    }
}
